#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QString>
#include<QUrl>
#include<QByteArray>
#include<QJsonDocument>
#include<QDebug>
#include<QJsonObject>
#include<QJsonArray>
#include<QImage>
#include<QPixmap>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initGetAccessToken();

    /* 信号与槽 */
    connect(ui->sendButton,&QPushButton::clicked,this,&MainWindow::chatGPTChat);
    connect(ui->picBtn,&QPushButton::clicked,this,&MainWindow::chatGPTImage);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initGetAccessToken()
{
    /* url 路径 */
    QString url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=y6hTXosWSXbbaREpC0DMF1pV&client_secret=PNtVgpMco3sJ5WGBjDsm5yeJHAkmMr8w";

    /* 设置URL */
    m_request.setUrl(QUrl(url));
    /* 设置HTTP请求头部 */
    m_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");

    /* 发送post请求 */
    /* 响应 */
    QNetworkReply * reply = m_manager.post(m_request,"");

    connect(reply,&QNetworkReply::finished,[this,reply]()
    {
        /* 判断响应是否出错 */
        if(reply->error() == QNetworkReply::NoError)
        {
            QByteArray content = reply->readAll();
            auto obj = QJsonDocument::fromJson(content);

            m_accessToken = obj["access_token"].toString();
            qDebug()<<"m_accessToken = "<<m_accessToken;
        }
        else
        {
            qDebug()<<"reply error";
        }
    });
}

/* 智能对话 */
void MainWindow::chatGPTChat()
{
     /* 设置URL路径 */
    QString url = QString("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat?access_token=") + m_accessToken;
    m_request.setUrl(QUrl(url));

    /* 设置HTTP请求头部 */
    m_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");

#if 1

    QJsonObject obj;

    /* 封装发送的内容 */
    QJsonArray jsonArray;
    QJsonObject chatObj;
    chatObj["role"] = "user";
    chatObj["content"] = ui->sendMsg->toPlainText();
    /* 将json对象放入到json数组中 */
    jsonArray.append(chatObj);

    obj["messages"] = jsonArray;

#endif

    QNetworkReply * reply = m_manager.post(m_request,QJsonDocument(obj).toJson());

    connect(reply,&QNetworkReply::finished,[this,reply]()
    {
        /* 判断响应是否出错 */
        if(reply->error() == QNetworkReply::NoError)
        {
            QByteArray content = reply->readAll();
            qDebug() << "API Response: " << content;  // 打印完整的响应内容
            auto obj = QJsonDocument::fromJson(content);

            QString result = obj["result"].toString();
            ui->recvMsg->setText(result);
            qDebug()<<"result"<<result;
        }
        else
        {
            qDebug()<<"reply error";
        }
    });
}


/* 智能文生图 */
void MainWindow::chatGPTImage()
{
    /* 设置URL路径 */
    QString url = QString("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/text2image/sd_xl?access_token=") + m_accessToken;
    m_request.setUrl(QUrl(url));

    /* 设置HTTP请求头部 */
    m_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");

    QJsonObject obj;
    obj["prompt"] = ui->sendMsg->toPlainText();

    /* 发送数据到百度大模型服务器 */
    QNetworkReply * reply = m_manager.post(m_request,QJsonDocument(obj).toJson());

    connect(reply,&QNetworkReply::finished,[this,reply]()
    {
        /* 判断响应是否出错 */
        if(reply->error() == QNetworkReply::NoError)
        {
            QByteArray content = reply->readAll();
            auto obj = QJsonDocument::fromJson(content);
            qDebug() << "obj: " << obj;

            auto arrayObj = obj["data"].toArray();
            if(arrayObj.size() == 0)
            {
                qDebug()<<"获取图片失败";
            }
            else
            {
                /* 图片的数据 */
                auto imageData = arrayObj[0].toObject()["b64_image"].toString().toUtf8();

                QImage image;
                image.loadFromData(imageData);

                ui->recvPic->setPixmap(QPixmap::fromImage(image).scaled(ui->recvPic->size()));
            }
        }
        else
        {
            qDebug()<<"reply image error";
        }
    });
}




